import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
  Dimensions,
} from 'react-native';
import { AIScoringService, AIScoreResult } from '../services/aiScoring';
import { VehicleFormData } from '../types';

const { width } = Dimensions.get('window');

interface AIScoringCardProps {
  vehicleData: VehicleFormData;
  onScoreComplete?: (result: AIScoreResult) => void;
}

const AIScoringCard: React.FC<AIScoringCardProps> = ({
  vehicleData,
  onScoreComplete,
}) => {
  const [isLoading, setIsLoading] = useState(false);
  const [scoreResult, setScoreResult] = useState<AIScoreResult | null>(null);

  const handleAIScoring = async () => {
    if (!vehicleData.brand || !vehicleData.model || !vehicleData.price) {
      Alert.alert('提示', '请先完善车辆基本信息');
      return;
    }

    setIsLoading(true);
    try {
      // 这里可以选择使用OpenAI或百度AI
      const result = await AIScoringService.scoreWithOpenAI(vehicleData);
      setScoreResult(result);
      onScoreComplete?.(result);
    } catch (error: any) {
      Alert.alert('评分失败', error.message || 'AI评分服务暂时不可用');
    } finally {
      setIsLoading(false);
    }
  };

  const getScoreColor = (score: number) => {
    if (score >= 4.5) return '#4CAF50'; // 绿色
    if (score >= 3.5) return '#FF9800'; // 橙色
    if (score >= 2.5) return '#FFC107'; // 黄色
    return '#F44336'; // 红色
  };

  const getScoreLevel = (score: number) => {
    if (score >= 4.5) return '优秀';
    if (score >= 3.5) return '良好';
    if (score >= 2.5) return '一般';
    return '较差';
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>AI智能评分</Text>
        <Text style={styles.subtitle}>基于车辆信息的专业评估</Text>
      </View>

      {!scoreResult ? (
        <View style={styles.scoringSection}>
          <TouchableOpacity
            style={[styles.scoreButton, isLoading && styles.disabledButton]}
            onPress={handleAIScoring}
            disabled={isLoading}
          >
            {isLoading ? (
              <ActivityIndicator color="#fff" />
            ) : (
              <Text style={styles.scoreButtonText}>开始AI评分</Text>
            )}
          </TouchableOpacity>
          <Text style={styles.tip}>
            评分范围：0-5分，支持一位小数
          </Text>
        </View>
      ) : (
        <View style={styles.resultSection}>
          <View style={styles.scoreDisplay}>
            <Text style={styles.scoreLabel}>综合评分</Text>
            <Text style={[styles.scoreValue, { color: getScoreColor(scoreResult.score) }]}>
              {scoreResult.score.toFixed(1)}
            </Text>
            <Text style={[styles.scoreLevel, { color: getScoreColor(scoreResult.score) }]}>
              {getScoreLevel(scoreResult.score)}
            </Text>
          </View>

          <View style={styles.confidenceBar}>
            <Text style={styles.confidenceLabel}>置信度</Text>
            <View style={styles.progressBar}>
              <View 
                style={[
                  styles.progressFill, 
                  { width: `${scoreResult.confidence * 100}%` }
                ]} 
              />
            </View>
            <Text style={styles.confidenceValue}>
              {(scoreResult.confidence * 100).toFixed(0)}%
            </Text>
          </View>

          <View style={styles.reasoningSection}>
            <Text style={styles.reasoningTitle}>评分理由</Text>
            <Text style={styles.reasoningText}>{scoreResult.reasoning}</Text>
          </View>

          {scoreResult.suggestions.length > 0 && (
            <View style={styles.suggestionsSection}>
              <Text style={styles.suggestionsTitle}>改进建议</Text>
              {scoreResult.suggestions.map((suggestion, index) => (
                <View key={index} style={styles.suggestionItem}>
                  <Text style={styles.suggestionBullet}>•</Text>
                  <Text style={styles.suggestionText}>{suggestion}</Text>
                </View>
              ))}
            </View>
          )}

          <TouchableOpacity
            style={styles.rescoreButton}
            onPress={() => setScoreResult(null)}
          >
            <Text style={styles.rescoreButtonText}>重新评分</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 16,
    margin: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  header: {
    marginBottom: 16,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 14,
    color: '#666',
  },
  scoringSection: {
    alignItems: 'center',
    paddingVertical: 20,
  },
  scoreButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
    marginBottom: 12,
  },
  disabledButton: {
    backgroundColor: '#ccc',
  },
  scoreButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  tip: {
    fontSize: 12,
    color: '#999',
    textAlign: 'center',
  },
  resultSection: {
    gap: 16,
  },
  scoreDisplay: {
    alignItems: 'center',
    paddingVertical: 16,
  },
  scoreLabel: {
    fontSize: 14,
    color: '#666',
    marginBottom: 8,
  },
  scoreValue: {
    fontSize: 48,
    fontWeight: 'bold',
    marginBottom: 4,
  },
  scoreLevel: {
    fontSize: 16,
    fontWeight: '600',
  },
  confidenceBar: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  confidenceLabel: {
    fontSize: 14,
    color: '#666',
    width: 60,
  },
  progressBar: {
    flex: 1,
    height: 8,
    backgroundColor: '#f0f0f0',
    borderRadius: 4,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    backgroundColor: '#007AFF',
  },
  confidenceValue: {
    fontSize: 12,
    color: '#666',
    width: 40,
    textAlign: 'right',
  },
  reasoningSection: {
    gap: 8,
  },
  reasoningTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
  },
  reasoningText: {
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
  },
  suggestionsSection: {
    gap: 8,
  },
  suggestionsTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
  },
  suggestionItem: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    gap: 8,
  },
  suggestionBullet: {
    fontSize: 14,
    color: '#007AFF',
    marginTop: 2,
  },
  suggestionText: {
    flex: 1,
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
  },
  rescoreButton: {
    backgroundColor: '#f0f0f0',
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 8,
  },
  rescoreButtonText: {
    color: '#666',
    fontSize: 14,
    fontWeight: '500',
  },
});

export default AIScoringCard; 